package com.liver_cloud.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloopen.rest.sdk.utils.encoder.BASE64Decoder;
import com.cloopen.rest.sdk.utils.encoder.BASE64Encoder;
import com.liver_cloud.dao.mybatis.DaoSupport;
import com.liver_cloud.service.common.CommonService;



public class ImageUpLoader {
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param identity 上传人身份，
	 * @throws ServletException
	 * @throws IOException
	 * @throws FileUploadException
	 */
	public   String saveCertificate(HttpServletRequest request,DaoSupport dao)
			throws ServletException, IOException, FileUploadException {
		request.setCharacterEncoding("UTF-8");
		String userId="";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		JSONArray volist = new JSONArray();
		JSONObject vo = null;
		String realImageRootDir = "/mnt/public2/liver/mydoctor/";///mnt/public2/liver/doctor/
		//String realImageRootDir = "C:/Program Files/apache-tomcat-8.0.35/webapps/my_doctor/p/";
		Date date = new Date();
		SimpleDateFormat simple = new SimpleDateFormat("yyyy/MM/dd");
		String nowDate = simple.format(date);
		String realpatch = realImageRootDir + nowDate;
		File f = new File(realpatch);
		if(!f.exists()){
			f.mkdirs();
		}		
		List<FileItem> items = upload.parseRequest(request);
			if(items.size()>0){
				for(FileItem item : items){
					if(!item.isFormField()){
						if (item.getName() != null
								&& !item.getName().equals("")) {
							vo = new JSONObject();
							vo.put("size", item.getSize());
							vo.put("contentType", item.getContentType());
							 System.out.println("上传文件的类型:" +
							 item.getContentType());
							vo.put("name", item.getName());
							 System.out.println("上传文件的名称:" + item.getName());
							 //上传文件的保存路径
							 File file = null;
								// File tempFile = new File(item.getName());
								String extName = FileUtil.getExtensionName(item
										.getName());
								String pictureId = UUID.randomUUID().toString();
								if (null != extName && !"".equals(extName)) {
									file = new File(realpatch, pictureId + "."
											+ extName);
								} else {
									file = new File(realpatch, pictureId);
								}
								try {
									item.write(file);
								} catch (Exception e) {
									e.printStackTrace();
									item.delete();
									continue;
								}
								String pictureUrl = "http://camp.liver-cloud.com/liver"+"/mydoctor/"
										+nowDate+ "/"
										+ pictureId + "." + extName;
								/*String pictureUrl = "http://10.0.1.73:8080"+"/my_doctor/p/"
										+nowDate+ "/"
										+ pictureId + "." + extName;*/
								vo.put("localPath", file.getPath());
								vo.put("pictureUrl", pictureUrl);
								System.out
										.println("uploadObject: " + vo.toString());
								volist.add(vo);
								item.delete();
							}
						} else {
							if ("userId".equals(item.getFieldName())
									&& null != item.getFieldName()) {
								userId = item.getString();
							}
						}
					}
					String imageUrl="";
					if (null != userId && !"".equals(userId)){
						for (int i = 0; i < volist.size(); i++) {
							JSONObject j = volist.getJSONObject(i);
							new Thread(new MRunner(userId,date,dao,
									j.getString("pictureUrl"))).run();
							imageUrl = j.getString("pictureUrl");
						}
						return imageUrl;
				}			
			}
			return null;
	}
	private class MRunner implements Runnable {
		private String userId = "";
		private String url = "";
		private Date date;
		private DaoSupport dao;
		private String personIdentity ="";
		public MRunner(String userId,Date date,DaoSupport dao, String url) {
			this.userId = userId;
			this.url = url;
			this.date = date;
			this.dao = dao;
			this.personIdentity= personIdentity;
		}

		@Override
		public void run() {
			//医生上传资格证书
			PageData temp = new PageData();
			temp.put("userId", userId);
			temp.put("imageUrl", url);
			temp.put("date", date);
				//向医生表中添加数据			
				try {					
					dao.update("DoctorMapper.uploadCertificate", temp);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
		}
	}
	/**
	 * 上传化验单接口,64进制数组
	 * @param pd
	 * @param dao
	 * @return
	 */
	public static PageData saveTestReport(PageData pd, DaoSupport dao) {
		// TODO Auto-generated method stub
		String userId = pd.getString("userId");
		String testReprotTime = pd.getString("testReprotTime");
		String img = pd.getString("imageContent");//"
		String[] content = img.split(",");
		String imgFormat = content[0].split(";")[0].split("/")[1];
		String realImageRootDir = "/mnt/public2/liver/mydoctor/";
		//String realImageRootDir = "C:/Program Files/apache-tomcat-8.0.35/webapps/my_doctor/p/";
		Date date = new Date();
		SimpleDateFormat simple = new SimpleDateFormat("yyyy/MM/dd");
		String nowDate = simple.format(date);
		String realpatch = realImageRootDir + nowDate;
		File f = new File(realpatch);
		if(!f.exists()){
			f.mkdirs();
		}
		String pictureId = UUID.randomUUID().toString();
		File file = new File(realpatch, pictureId + "."
				+ imgFormat);
		PageData result = new PageData();
		try{			
			 BASE64Decoder decoder = new BASE64Decoder();  
			 byte[] b = decoder.decodeBuffer(content[1]);
			//读取
			/* 
			 for(int i=0;i<b.length;++i)  
	            {  
	                if(b[i]<0)  
	                {//调整异常数据  
	                    b[i]+=256;  
	                }  
	            }  */
			FileOutputStream out = new FileOutputStream(file);
			out.write(b);
			out.flush();
			out.close();
			/*String pictureUrl = "http://10.0.1.73:8080"+"/my_doctor/p/"
					+nowDate+ "/"
					+ pictureId + "." + imgFormat;*/
			String pictureUrl = "http://camp.liver-cloud.com/liver"+"/mydoctor/"
					+nowDate+ "/"
					+ pictureId + "." + imgFormat;
			//保存图片信息到md_test_report表
			PageData temp = new PageData();
			Long time = Long.parseLong(testReprotTime);
			Date reportDate = new Date(time);
			Date now = new Date();
			temp.put("createTime", now);
			temp.put("reportDate", reportDate);
			temp.put("userId", userId);
			temp.put("pictureUrl", pictureUrl);
			dao.save("PatientMapper.saveTestReport", temp);
			//找到新插入的数据
			result =  
					(PageData) dao.findForObject("PatientMapper.getTestReport", temp);
			
			}catch(Exception e){
			e.printStackTrace();
			}		
		return result;
	}

	public static PageData savePatientTestReport(HttpServletRequest request,
			DaoSupport dao) throws Exception {

		request.setCharacterEncoding("UTF-8");
		PageData result = new PageData();
		String userId="";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		JSONArray volist = new JSONArray();
		JSONObject vo = null;
		String realImageRootDir = "/mnt/public2/liver/mydoctor/";///mnt/public2/liver/doctor/
		//String realImageRootDir = "C:/Program Files/apache-tomcat-8.0.35/webapps/my_doctor/p/";
		Date date = new Date();
		String imageUrl="";
		Date testReprotDate = new Date();
		SimpleDateFormat simple = new SimpleDateFormat("yyyy/MM/dd");
		String nowDate = simple.format(date);
		String realpatch = realImageRootDir + nowDate;
		File f = new File(realpatch);
		if(!f.exists()){
			f.mkdirs();
		}		
		List<FileItem> items = upload.parseRequest(request);
			if(items.size()>0){
				for(FileItem item : items){
					if(!item.isFormField()){
						if (item.getName() != null
								&& !item.getName().equals("")) {
							vo = new JSONObject();
							vo.put("size", item.getSize());							
							vo.put("contentType", item.getContentType());
							 System.out.println("上传文件的类型:" +
							 item.getContentType());
							vo.put("name", item.getName());
							 System.out.println("上传文件的名称:" + item.getName());
							 //上传文件的保存路径
							 File file = null;
							 File scaledFile = null;
								// File tempFile = new File(item.getName());
								String extName = FileUtil.getExtensionName(item
										.getName());
								String pictureId = UUID.randomUUID().toString();
								//缩略图url
								/*String pictureUrl = "http://10.0.1.73:8080"+"/my_doctor/p/"
								+nowDate+ "/"
								+ pictureId + "." + extName;
								String scaledPictureUrl = "http://10.0.1.73:8080"+"/my_doctor/p/"
								+nowDate+ "/"
								+ pictureId +"scaled"+ "." + extName;*/
								String scaledPictureUrl = "http://camp.liver-cloud.com/liver"+"/mydoctor/"
										+nowDate+ "/"
										+ pictureId +"scaled"+ "." + extName;							
								String pictureUrl = "http://camp.liver-cloud.com/liver"+"/mydoctor/"
										+nowDate+ "/"
										+ pictureId + "." + extName;
								if (null != extName && !"".equals(extName)) {
									file = new File(realpatch, pictureId + "."
											+ extName);
									scaledFile =new File(realpatch, pictureId+"scaled" + "."
											+ extName);
								} else {
									file = new File(realpatch, pictureId);
									scaledFile = new File(realpatch, pictureId+"scaled");
								}
								try {
									item.write(file);
									//如果图片大于1M就压缩
									if(item.getSize()>1024*1024){
										Thumbnails.of(file).scale(0.2f).toFile(scaledFile);
									}else{
										//缩略图路径和原图路径一致
										scaledPictureUrl = pictureUrl;
									}									
								} catch (Exception e) {
									e.printStackTrace();
									item.delete();
									continue;
								}
								/*String pictureUrl = "http://10.0.1.73:8080"+"/my_doctor/p/"
										+nowDate+ "/"
										+ pictureId + "." + extName;*/
								vo.put("scaledPictureUrl", scaledPictureUrl);
								vo.put("localPath", file.getPath());
								vo.put("pictureUrl", pictureUrl);
								System.out
										.println("uploadObject: " + vo.toString());
								volist.add(vo);
								item.delete();
							}
						} else {
							if ("userId".equals(item.getFieldName())
									&& null != item.getFieldName()) {
								userId = item.getString();
							}else if("testReprotTime".equals(item.getFieldName())){								
								String reportTime = item.getString();
								Long timeLong = Long.valueOf(reportTime);
								testReprotDate.setTime(timeLong);
							}
						}
					}					

					if (null != userId && !"".equals(userId)){
							JSONObject j = volist.getJSONObject(0);
							//保存数据
							PageData temp = new PageData();
							imageUrl = j.getString("pictureUrl");
							temp.put("pictureUrl", imageUrl);
							temp.put("scaledPictureUrl", j.getString("scaledPictureUrl"));
							temp.put("userId", userId);
							temp.put("createTime", new Date());
							temp.put("reportDate", testReprotDate);
							dao.save("PatientMapper.saveTestReport", temp);
							result =  
									(PageData) dao.findForObject("PatientMapper.getTestReport", temp);
				}			
			}
			return result;
	}
	
	//上传或更新推送消息
	public static PageData saveOrUpdatePushMessage(HttpServletRequest request,
			DaoSupport dao, CommonService commonService) throws Exception {
		// 
		PageData pd = new PageData();// 存放数据
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		//存放集合
				JSONArray volist = new JSONArray();
				JSONObject vo = null;
				String realImageRootDir = "/mnt/public2/liver/mydoctor/";///mnt/public2/liver/doctor/
				Date date = new Date();
				SimpleDateFormat simple = new SimpleDateFormat("yyyy/MM/dd");
				String nowDate = simple.format(date);
				String realpatch = realImageRootDir + nowDate;
				File f = new File(realpatch);
				if(!f.exists()){
					f.mkdirs();
				}
		List<FileItem> items = upload.parseRequest(request);
		//遍历，拿取数据
		String pushType = "";
		String title = "";
		String content = "";
		String type="";
		String permissionLevel = "";
		String diagnosisType ="";
		String pushMessageId ="";
		if(items.size()==0){
			return null;
		}
		if(items.size()>0){
			//遍历获取字段值
			for(FileItem item : items){
				if(item.isFormField()){
					//如果item是字段类型，获取item对应的key
					//先获取pushType，发布新推送和修改推送逻辑不同
					if("pushType".equals(item.getFieldName())){
						pushType = item.getString();
						pd.put("pushType", pushType);
					}else if("title".equals(item.getFieldName())){
						String titleTemp = item.getString();
						title = java.net.URLDecoder.decode(titleTemp, "UTF-8");	
						pd.put("title", title);
					}else if("content".equals(item.getFieldName())){
						String contentTemp = item.getString();
						content = java.net.URLDecoder.decode(contentTemp, "UTF-8");	
						pd.put("content", content);
					}else if("userId".equals(item.getFieldName())){
						pd.put("userId", item.getString());
					}else if("type".equals(item.getFieldName())){
						type = item.getString();
						pd.put("type", item.getString());
					}else if("permissionLevel".equals(item.getFieldName())){
						permissionLevel = item.getString();
						pd.put("permissionLevel", item.getString());
					}else if("diagnosisType".equals(item.getFieldName())){
						pd.put("diagnosisType", item.getString());
					}else if("diagnosisType".equals(item.getFieldName())){
						diagnosisType = item.getString();
						pd.put("diagnosisType", item.getString());
					}else if("pushMessageId".equals(item.getFieldName())){
						pushMessageId = item.getString();
						pd.put("pushMessageId", item.getString());
					}					
				}
			}
			//保存图片
			for(FileItem item : items){
				//不再是图片文件
				if(!item.isFormField()){
					vo = new JSONObject();
					File file = null;
					String extName = FileUtil.getExtensionName(item
							.getName());
					String pictureId = UUID.randomUUID().toString();
					file = new File(realpatch, pictureId + "."
							+ extName);
					try {									
						item.write(file);
					} catch (Exception e) {
						e.printStackTrace();
						item.delete();
						continue;
					}
					String pictureUrl = "http://camp.liver-cloud.com"+"/liver/mydoctor/"
							+nowDate+ "/"
							+ pictureId + "." + extName;
					vo.put("pictureUrl", pictureUrl);
					volist.add(vo);
					item.delete();
				}
				
			}
			//根据pushType 选择该走的逻辑，1：新的消息推送；2：编辑已推送的消息
			if("1".equals(pushType)){
				//先保存基本消息，获取新插入的pushMessageId
				Date dateTemp = new Date();
				pd.put("date", dateTemp);
				dao.save("AssistantMapper.savePushMessage", pd);
				//根据用户名，时间查询刚插入的新推送消息Id
				pushMessageId = 
						(String) dao.findForObject("AssistantMapper.getPushMessageId", pd);
				pd.put("pushMessageId", pushMessageId);
				//向权限表中添加信息
				dao.save("AssistantMapper.savePermisition", pd);
				//想图片表中插入信息
				for(int i = 0; i < volist.size(); i++){
					JSONObject j = volist.getJSONObject(i);
					pd.put("pictureUrl", j.getString("pictureUrl"));
					dao.save("AssistantMapper.insertPicture", pd);
				}
				//想将发起者插入表
				dao.save("AssistantMapper.saveSelfPermisition", pd);
				//向md_permission_person表中添加符合条件的人，包括自己
				if("0".equals(type)){//助手推送的消息
					//将和这个助手相关联的医生，加入到表中
					List<PageData> doctorInfo = 
							(List<PageData>) dao.findForList("AssistantMapper.getDoctorList", pd);
					for(int j=0;j<doctorInfo.size();j++){
						doctorInfo.get(j).put("pushMessageId", pushMessageId);
						dao.save("AssistantMapper.inserPermisitionPerson", doctorInfo.get(j));
					}
					//找到隶属于这个助手的医生
					String doctorId = 
							(String) dao.findForObject("AssistantMapper.getDoctorId", pd);					
					//将和这个助手相关的患者加入表中
					if("3".equals(permissionLevel)){//所有患者可看
						List<PageData> patientInfo = 
								(List<PageData>) dao.findForList("AssistantMapper.getPatientList", pd);
						for(int j=0;j<patientInfo.size();j++){
							patientInfo.get(j).put("pushMessageId", pushMessageId);
							dao.save("AssistantMapper.savePatientPermisition", patientInfo.get(j));
						}
					}else{
						//查询符合条件的患者
						String[] tempArray = permissionLevel.split(",");
						PageData tempPd = new PageData();
						tempPd.put("doctorId", doctorId);
						tempPd.put("tempArray", tempArray);
						List<PageData> patientInfo = 
								(List<PageData>) dao.findForList("AssistantMapper.getPatientByPermission", tempPd);
						for(int j=0;j<patientInfo.size();j++){
							patientInfo.get(j).put("pushMessageId", pushMessageId);
							dao.save("AssistantMapper.savePatientPermisition", patientInfo.get(j));
						}
						
					}
					
				}else{
					//医生添加推送消息，所有助手，所有人（助手和患者），部分患者。对应的permissionLevel：2,1,4
					if("1".equals(permissionLevel)||"2".equals(permissionLevel)){//将所有助手加入表						
						List<PageData> assistantInfo = 
								(List<PageData>) dao.findForList("AssistantMapper.getAssistantList", pd);
						/*//将助手平台id插入表中
						PageData temp = new PageData();
						temp.put("pushMessageId", pushMessageId);
						temp.put("type", "2");
						temp.put("list", assistantInfo);
						dao.save("AssistantMapper.batchSaveAssistantPermisition", temp);	*/				
						for(int j=0;j<assistantInfo.size();j++){
							assistantInfo.get(j).put("pushMessageId", pushMessageId);
							assistantInfo.get(j).put("type", "2");
							dao.save("AssistantMapper.saveAssistantPermisition", assistantInfo.get(j));							
						}
						if("1".equals(permissionLevel)){//同时将所有患者加入表
							List<PageData> patientInfo = 
									(List<PageData>) dao.findForList("DoctorMapper.getAllPatient", pd);							
							for(int j=0;j<assistantInfo.size();j++){
								assistantInfo.get(j).put("pushMessageId", pushMessageId);
								assistantInfo.get(j).put("type", "3");
								dao.save("AssistantMapper.saveAssistantPermisition", assistantInfo.get(j));							
							}
						}
						
					}else if("4".equals(permissionLevel)){//部分患者插入
						String[] tempArray = permissionLevel.split(",");
						pd.put("tempArray", tempArray);
						 List<PageData> patientList = 
								 (List<PageData>) dao.findForList("DoctorMapper.getPermissionPatient", pd);
						 for(int j=0;j<patientList.size();j++){
							 patientList.get(j).put("pushMessageId", pushMessageId);
							 patientList.get(j).put("type", "3");
							 dao.save("AssistantMapper.saveAssistantPermisition", patientList.get(j));							
							}
						
					}
				
				}
				
			}else{
				//编辑推送的消息，权限不能更改.根据pushMessageId 保存新的东西，删除原来的图片文件
				//第一步，更新基本信息
				Date changeDate = new Date();
				pd.put("changeDate", changeDate);
				dao.update("AssistantMapper.updatePushMessage", pd);
				//第二步。删除已上传的图片
				List<String> pictureList = 
						(List<String>) dao.findForList("AssistantMapper.getPictureList", pd);
				dao.delete("AssistantMapper.deletePicture", pd);
				for(int i=0;i<pictureList.size();i++){
					String url = pictureList.get(i);
					url.replace("http://camp.liver-cloud.com", "/mnt/public2");
					FileUtil.delFile(url);					
				}
				//插入新的图片
				for(int i = 0; i < volist.size(); i++){
					JSONObject j = volist.getJSONObject(i);
					pd.put("pictureUrl", j.getString("pictureUrl"));
					dao.save("AssistantMapper.insertPicture", pd);
				}				
			}
						
		}
		PageData result = new PageData();
		result.put("pushMessageId", pushMessageId);		
		return result;
	}

	
	

}
